package com.ipt.frm.pw;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.DiskFileUpload;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import org.apache.tomcat.util.http.fileupload.FileUploadException;

/**
 * Servlet implementation class Ficheros
 */
public class Ficheros extends HttpServlet {
	private static final long serialVersionUID = 1184213685238232730L;
	Properties prop = null;
	String rutaConfig = "";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Ficheros() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		String fileName = "";

		if (FileUpload.isMultipartContent(request) == false) {
			/**
			 * Redireccion a la pagina 'pruebafichero.jsp' para indicarle el
			 * titulo
			 */
			request.setAttribute("title", "Prueba subida de ficheros");
			request.getRequestDispatcher("/pruebafichero.jsp").forward(request,
					response);
		} else {

			/**
			 * Subida de ficheros al servidor
			 * 
			 * 
			 */

			try {
				// first check if the upload request coming in is a multipart
				// request
				boolean isMultipart = FileUpload.isMultipartContent(request);
				log("content-length: " + request.getContentLength());
				log("method: " + request.getMethod());
				log("character encoding: " + request.getCharacterEncoding());

				if (isMultipart) {
					DiskFileUpload upload = new DiskFileUpload();
					List items = null;

					try {
						// parse this request by the handler
						// this gives us a list of items from the request
						items = upload.parseRequest(request);
						log("items: " + items.toString());
					} catch (FileUploadException ex) {
						log("Failed to parse request", ex);
					}
					Iterator itr = items.iterator();

					while (itr.hasNext()) {
						FileItem item = (FileItem) itr.next();

						// check if the current item is a form field or an
						// uploaded
						// file
						if (item.isFormField()) {
							// get the name of the field
							String fieldName = item.getFieldName();
							out.print(fieldName + ": " + item.getString()
									+ "<br />");
						} else {
							fileName = subidaArchivos(item, request);

							request.setAttribute("urlFichero", "ficheros/"
									+ fileName);

							out.print(request.getAttribute("urlFichero"));

							RequestDispatcher dispatcher = this
									.getServletContext().getRequestDispatcher(
											"/pruebafichero.jsp");
							dispatcher.forward(request, response);
						}
					}

				}

			} finally {
				out.close();
			}
		}
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		// TODO Ruta Relativa
		rutaConfig = "C:/desarrollo/workspace/PruebasWeb/WebContent/config/configuracion.properties";
		FileInputStream fis;
		prop = new Properties();
		try {
			fis = new FileInputStream(rutaConfig);
			prop.load(fis);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		super.service(request, response);
	}

	/**
	 * the item must be an uploaded file save it to disk. Note that there seems
	 * to be a bug in item.getName() as it returns the full path on the client's
	 * machine for the uploaded file name, instead of the file name only. To
	 * overcome that, I have used a workaround using fullFile.getName().
	 * 
	 * @param item
	 * @param request
	 * 
	 * @see http ://javaevangelist.blogspot.com.es/2013/09/apache-commons-file
	 *      -upload-servlet.html
	 * @return
	 */
	private String subidaArchivos(FileItem item, HttpServletRequest request) {
		String fileName = "";

		String realPath = prop.getProperty("rutaServidor") + "/";
		new File(request.getRealPath("users") + "/me@this.com").mkdir();

		File fullFile = new File("/" + item.getName());
		fileName = fullFile.getName();
		File savedFile = new File(realPath, fullFile.getName());

		try {
			item.write(savedFile);
		} catch (Exception ex) {
			log("Failed to save file", ex);
		}

		return fileName;
	}

}
